﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Bonobo.Irc
{
    public sealed class IrcStringComparer : IEqualityComparer<String>
    {
        private static readonly IEqualityComparer<String> RealComparer = StringComparer.OrdinalIgnoreCase;

        private IrcStringComparer()
        {
        }

        public Boolean Equals(String x, String y)
        {
            if (ReferenceEquals(x, y))
            {
                return true;
            }

            if (ReferenceEquals(x, null) ||
                ReferenceEquals(y, null))
            {
                return false;
            }

            x = Normalize(x);
            y = Normalize(y);

            return RealComparer.Equals(x, y);
        }

        public Int32 GetHashCode(String obj)
        {
            if (!String.IsNullOrEmpty(obj))
            {
                obj = Normalize(obj);
            }

            return RealComparer.GetHashCode(obj);
        }

        public static IEqualityComparer<String> OrdinalIgnoreCase
        {
            get { return _instance; }
        }

        private static String Normalize(String s)
        {
            var result = new StringBuilder(s.Length);

            for (int i = 0; i < s.Length; i++)
            {
                if ((s[i] >= '{') && (s[i] <= '}'))
                {
                    result.Append((Char)(s[i] - 32));
                }
                else if (s[i] == '^')
                {
                    result.Append('~');
                }
                else
                {
                    result.Append(s[i]);
                }
            }

            return result.ToString();
        }

        private static IrcStringComparer _instance = new IrcStringComparer();
    }
}
